package com.imooc.miaosha.controller.FeController;

import com.alibaba.fastjson.TypeReference;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.imooc.miaosha.common.Const;
import com.imooc.miaosha.dto.GoodsVO;
import com.imooc.miaosha.dto.SecondKillDetailVO;
import com.imooc.miaosha.service.GoodsService;
import com.imooc.miaosha.service.SolrService;
import com.imooc.miaosha.service.impl.SolrServiceImpl;
import com.imooc.miaosha.util.JedisUtil;
import com.imooc.miaosha.util.JsonData;
import com.imooc.miaosha.util.JsonUtil;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.context.annotation.RequestScope;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;


import static com.imooc.miaosha.common.Const.RANK_SET_KEY;

@Controller
@Slf4j
@RequestMapping("goods")
public class GoodsController {
    public static final Cache<String, List<GoodsVO>> goodsCache = CacheBuilder.newBuilder().expireAfterAccess(120, TimeUnit.SECONDS).build();

    @Autowired
    GoodsService goodsService;
    @Autowired
    ThymeleafViewResolver thymeleafViewResolver;

    @RequestMapping("search")
    @ResponseBody
    public JsonData search(@RequestBody Map<String, Object> map) throws IOException, SolrServerException {

        String q = (String) map.get("q");
        Integer start = (Integer) map.get("start");

        HttpSolrClient solrClient = new HttpSolrClient.Builder("http://122.112.167.247:8984/solr/product")
                .build();
        SolrService solrService = new SolrServiceImpl(solrClient);
        List<Integer> idList = solrService.queryIndex(q, "id", start);
        if (idList.size() == 0) {
            return JsonData.fail("搜索无内容");
        }
        double count = JedisUtil.zincrby(q, Const.RANK_SET_KEY, 1.0d);
        //未创建这个set的key
        if (count == Const.UN_CREATE_RANK_SET_KEY) {
            JedisUtil.zadd(RANK_SET_KEY, q, 1.0);
        }

        return JsonData.success(goodsService.searchByIdList(idList));
    }

    @RequestMapping("getSearchRank")
    @ResponseBody
    public JsonData rank() {
        Set<Tuple> keySet = JedisUtil.zrangeReverseWithScores(Const.RANK_SET_KEY, 0, 10);
        return JsonData.success(keySet);
    }

    // TODO: 2020/4/28 小程序缓存接口
    @RequestMapping(value = "good_list_json")
    @ResponseBody
    public JsonData listMini() {
        List<GoodsVO> goodsVOList = goodsCache.getIfPresent("good_list_cache");
        if (goodsVOList != null) {
            return JsonData.success(goodsVOList);
        }
        String miaoshaGoodsJson = JedisUtil.get(Const.GOOD_LIST_JSON_CACHE_PREFIX, "");
        if (miaoshaGoodsJson != null) {
            List<GoodsVO> goodsVO = JsonUtil.String2Obj(miaoshaGoodsJson, new TypeReference<List<GoodsVO>>() {
            });
            return JsonData.success(goodsVO);
        }
        goodsVOList = goodsService.list();
        JedisUtil.setEx(Const.GOOD_LIST_JSON_CACHE_PREFIX, "", JsonUtil.Obj2String(goodsVOList), Const.GOOD_LIST_JSON_CACHE_EXPIRE);
        goodsCache.put("good_list_cache", goodsVOList);
        return JsonData.success(goodsVOList);
    }

    // TODO: 2020/4/28 pc缓存接口
    @RequestMapping(value = "goods_list", produces = "text/html")
    @ResponseBody
    public String list(HttpServletRequest request, HttpServletResponse response, Model model) {

        //取缓存
        String html = JedisUtil.get(Const.GOOD_LIST_PAGE_CACHE_PREFIX, "");

        if (!StringUtils.isEmpty(html)) {
            return html;
        }
        List<GoodsVO> goodsList = goodsService.list();
        //注意！
        model.addAttribute("goodsList", goodsList);
//    	 return "goods_list";
        WebContext ctx = new WebContext(request, response,
                request.getServletContext(), request.getLocale(), model.asMap());
        //手动渲染
        html = thymeleafViewResolver.getTemplateEngine().process("goods_list", ctx);
        if (!StringUtils.isEmpty(html)) {
            JedisUtil.setEx(Const.GOOD_LIST_PAGE_CACHE_PREFIX, "", html, Const.GOOD_LIST_PAGE_CACHE_EXPIRE);
        }
        return html;
    }

    @RequestMapping(value = "/detail/{id}")
    @ResponseBody
    public JsonData detail(@PathVariable Long id) {
        JedisUtil.incr(Const.COUNT_PREFIX, id.toString());
        String goodsDetailJson = JedisUtil.get("GOODS_DETAIL", id.toString());
        if (!StringUtils.isEmpty(goodsDetailJson)) {
            SecondKillDetailVO secondKillDetailVO = JsonUtil.String2Obj(goodsDetailJson, new TypeReference<SecondKillDetailVO>() {
            });
            return JsonData.success(secondKillDetailVO);
        }
        SecondKillDetailVO detailDTO = goodsService.getDetail(id);
        JedisUtil.setEx("GOODS_DETAIL", id.toString(), JsonUtil.Obj2String(detailDTO), 60);
        return JsonData.success(detailDTO);

    }

    @RequestMapping(value = "to_detail")
    public String toDetail() {
        return "miaosha_detail";
    }

}
